<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

class AuctionController extends JController
{
	/**
	 * Display the view
	 */
	function display()
	{
		parent::display();
	
	}
	
	function sendPrice()
	{
		$db = &JFactory::getDBO();
		
		$price = JRequest::getVar('price');
		$user_id = JRequest::getVar('user_id');
		$auc_id = JRequest::getVar('auc_id');
		
		$query = "SELECT closed FROM #__auction where id = ".$auc_id;  
		$db->setQuery($query);
		$closed = $db->loadResult();
		if($closed == 0){
			$query = "UPDATE #__auction SET currentprice = ".$price." WHERE id = ".$auc_id;
			$db->setQuery($query);
			$db->query();
			
			$query = "INSERT INTO #__auction_user (auction_id, user_id, price, aucdate) VALUES (".$auc_id.", ".$user_id.", ".$price.", now())";
			$db->setQuery($query);
			$db->query();
			
			do{
				$action = $this->autoBid($auc_id);
			} while($action == true);
						
			echo json_encode(array('closed' => $closed, 'price' => $price, TRUE));
		} else {
			echo json_encode(array('closed' => $closed, 'price' => $price, TRUE));
		}
		exit();
	}
	
	function loadPrice(){
		$db = &JFactory::getDBO();
		$user = JFactory::getUser();
		$auc_id = JRequest::getVar('auc_id');
		$query = "SELECT currentprice, closed, winid, desiredprice FROM #__auction WHERE id = ".$auc_id;  
		$db->setQuery($query);
		$auc = $db->loadObject();
		
		$query = "SELECT price FROM #__auction_user WHERE auction_id = ".$auc_id." AND user_id = ".$user->id." ORDER BY id DESC LIMIT 0,1";  
		$db->setQuery($query);
		$mycurrent = $db->loadResult();
		echo json_encode(array('closed' => $auc->closed, 'price' => $auc->currentprice, 'winid' => $auc->winid, 'mycurrent' => $mycurrent, TRUE));
		exit();
	}
	
	/*function loadPrice(){
		$db = &JFactory::getDBO();
		$user = JFactory::getUser();
		$auc_id = JRequest::getVar('auc_id');
		$currPrice = JRequest::getVar('price');
		
		$query = "SELECT currentprice, closed FROM #__auction WHERE id = ".$auc_id;  
		$db->setQuery($query);
		$auc = $db->loadObject();
		
		while(($currPrice == $auc->currentprice) || (!$auc->closed)){print_r($auc);exit;
			usleep(100000);
			
			$query = "SELECT currentprice, closed FROM #__auction WHERE id = ".$auc_id;  
			$db->setQuery($query);
			$auc = $db->loadObject();
		}
		
		echo json_encode(array('closed' => $auc->closed, 'price' => $auc->currentprice, TRUE));
		exit();
	}*/
	
	function loadStatus(){
		$db = &JFactory::getDBO();
		
		$currStatus = JRequest::getVar('status');
		
		$query = "SELECT auction_date FROM #__auction_date WHERE id = 2";  
		$db->setQuery($query);
		$status = $db->loadResult();
		
		if($currStatus != $status){
			echo 1;
			exit();
		} else {
			echo 0;
			exit();
		}
	}
	
	function endAuction(){
		$db = &JFactory::getDBO();
		$auc_id = JRequest::getVar('auc_id');
		
		$query = "SELECT user_id, price FROM #__auction_user WHERE auction_id = ".$auc_id." ORDER BY id DESC LIMIT 0,1";
		$db->setQuery($query);
		$auc_user = $db->loadObject();
		
		$query = "SELECT profile_number FROM #__users WHERE id = ".$auc_user->user_id;
		$db->setQuery($query);
		$pn = $db->loadResult();
		
		$query = "UPDATE #__auction SET closed = 1, winprice = ".$auc_user->price.", winid = '".$pn."'  WHERE id = ".$auc_id;
		$db->setQuery($query);
		$db->query();
		
		$query = "SELECT winprice, closed, product_id FROM #__auction where id = ".$auc_id;  
		$db->setQuery($query);
		$auc = $db->loadObject();
		
		$db->setQuery("UPDATE #__pr_product SET bought = 1 WHERE id = ".$auc->product_id);
		$db->query();
		$db->setQuery("UPDATE #__users SET buy = 1 WHERE id = ".$auc_user->user_id);
		$db->query();
		
		echo json_encode(array('closed' => $auc->closed, 'price' => $auc->winprice, TRUE));
		exit();
	}
	
	function saveProfileNumber(){
		$db = &JFactory::getDBO();
		$pn = JRequest::getVar('pn');
		$auc_id = JRequest::getVar('auc_id');
		
		$db->setQuery("UPDATE #__auction SET winid = '".$pn."' WHERE id = ".$auc_id);
		$db->query();
		
		$this->setRedirect($_SERVER['HTTP_REFERER']);
	}
	
	function startAuto(){
		$db = &JFactory::getDBO();
		$user = JFactory::getUser();
		$user_id = JRequest::getVar("user_id");
		$auc_id = JRequest::getVar("auc_id");
		$max_price = JRequest::getVar("max_price");

		$query = "INSERT INTO #__auction_auto (user_id, auc_id, max_price, status) VALUES (".$user_id.", ".$auc_id.", ".$max_price.", 0)";
		$db->setQuery($query);
		$db->query();
		
		$this->sendMail2($user_id, $auc_id, $max_price);
		
		do{
			$action = $this->autoBid($auc_id);
		} while($action == true);		
		
		echo 1; exit;
	}
	
	function stopAuto(){
		$db = &JFactory::getDBO();
		$user = JFactory::getUser();
		$user_id = JRequest::getVar("user_id");
		$auc_id = JRequest::getVar("auc_id");
		
		$query = "DELETE FROM #__auction_auto WHERE user_id = ".$user_id." AND auc_id = ".$auc_id;
		$db->setQuery($query);
		$db->query();
		
		echo 1; exit;
	}
	
	function autoBid($auc_id){
		$db = &JFactory::getDBO();
		$users = $this->getBidUsers($auc_id);
		if($users){
			foreach($users as $user){
				$currentprice = $this->getCurrentPrice($auc_id);
				if($user->max_price > $currentprice){
					if($user->max_price - $currentprice > 500) $stepPrice = 500;
					else $stepPrice = $user->max_price - $currentprice;
					$query = "UPDATE #__auction SET currentprice = currentprice + ".$stepPrice." WHERE id = ".$auc_id;
					$db->setQuery($query);
					$db->query();
					$price = $currentprice + $stepPrice;
					$query = "INSERT INTO #__auction_user (auction_id, user_id, price, aucdate) VALUES ('".$auc_id."', '".$user->user_id."', ".$price.", now())";
					$db->setQuery($query);
					$db->query();
				} else {
					$this->sendMail1($user->user_id, $auc_id);
					$query = "DELETE FROM #__auction_auto WHERE user_id = ".$user->user_id." AND auc_id = ".$auc_id;
					$db->setQuery($query);
					$db->query();
				}
			}
			return true;
		} else {
			return false;
		}
	}
	
	function getBidUsers($auc_id){
		$db = &JFactory::getDBO();
		
		$query = "SELECT user_id FROM #__auction_user WHERE auction_id = ".$auc_id." ORDER BY id DESC LIMIT 0,1";
		$db->setQuery($query);
		$user_id = $db->loadResult();
		
		if($user_id){
			$query = "SELECT user_id, max_price FROM #__auction_auto WHERE auc_id = ".$auc_id." AND user_id <> ".$user_id." ORDER BY id";
			$db->setQuery($query);
			$users = $db->loadObjectList();
		} else {
			$query = "SELECT user_id, max_price FROM #__auction_auto WHERE auc_id = ".$auc_id." ORDER BY id";
			$db->setQuery($query);
			$users = $db->loadObjectList();
		}

		return $users;
	}
	
	function getCurrentPrice($auc_id){
		$db = &JFactory::getDBO();
		
		$query = "SELECT currentprice FROM #__auction WHERE id = ".$auc_id;
		$db->setQuery($query);
		$currentprice = $db->loadResult();
		
		return $currentprice;
	}
	
	function sendMail1($userid, $auc_id){
		global $mainframe;
		$db = &JFactory::getDBO();
		
		$query = "SELECT * FROM #__users WHERE id = ".$userid;
		$db->setQuery($query);
		$user = $db->loadObject();
		
		$query = "SELECT p.model FROM #__auction as a INNER JOIN #__pr_product as p ON a.product_id = p.id WHERE a.id = ".$auc_id;
		$db->setQuery($query);
		$pro_name = $db->loadResult();
		
		$mailfrom 		= $mainframe->getCfg( 'mailfrom' );
		$fromname 		= $mainframe->getCfg( 'fromname' );
		$sitename 		= $mainframe->getCfg( 'sitename' );
		$subject 	= 'Info fra Dansk Automobil Børs';

		$message = 'Kære '.$user->name.',<br /><br />Din max. budpris til "'.$pro_name.'", er blevet overbudt af en anden budgiver. <br /><br />Med venlig hilsen<br />Dansk Automobil Børs';
		
		JUtility::sendMail($mailfrom, $fromname, $user->email, $subject, $message, true);
	}
	
	function sendMail2($userid, $auc_id, $max_price){
		global $mainframe;
		$db = &JFactory::getDBO();
		$user = JFactory::getUser($userid);
		
		$query = "SELECT p.model FROM #__auction as a INNER JOIN #__pr_product as p ON a.product_id = p.id WHERE a.id = ".$auc_id;
		$db->setQuery($query);
		$pro_name = $db->loadResult();
		
		$mailfrom 		= $mainframe->getCfg( 'mailfrom' );
		$fromname 		= $mainframe->getCfg( 'fromname' );
		$sitename 		= $mainframe->getCfg( 'sitename' );
		$subject 	= 'Info fra Dansk Automobil Børs';

		$message = 'Kære '.$user->name.',<br /><br />Vi har registreret dit max. budpris kr. '.number_format($max_price,0,",",".").' på "'.$pro_name.'"<br /><br />Med venlig hilsen<br />Dansk Automobil Børs';
		
		JUtility::sendMail($mailfrom, $fromname, $user->email, $subject, $message, true);
		return true;
	}
}	

?>